package com.amap.search.listener;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.amap.search.service.ElasticSearchOperatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class CanalListener {
    @Resource
    private ElasticSearchOperatorService elasticSearchOperatorService;

    private final static String targetDataBase = "db2022";
    private final static String targetTable = "poi_record";
    ExecutorService executor = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init(){
        executor.execute(this::contextLoads);
        log.info("Canal监听开始");
    }

    public void contextLoads() {
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("127.0.0.1", 11111), "example", "", "");
        try {
            //打开连接db2022库的poi_record表
            connector.connect();
            //只订阅
            connector.subscribe(targetDataBase + "\\." + targetTable);
            while (true) {
                // 获取指定数量的数据
                Message message = connector.getWithoutAck(100);
                //获取批量ID
                long batchId = message.getId();
                //获取批量的数量
                int size = message.getEntries().size();
                //如果没有数据
                if (batchId == -1 || size == 0) {
                    try {
                        //线程休眠5秒
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    //如果有数据,处理数据
                    synEntrys(message.getEntries());
                }
                //进行 batch id 的确认。确认之后，小于等于此 batchId 的 Message 都会被确认。
                connector.ack(batchId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connector.disconnect();
        }
    }

    private void synEntrys(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                //开启/关闭事务的实体类型，跳过
                continue;
            }
            //RowChange对象，包含了一行数据变化的所有特征
            //比如isDdl 是否是ddl变更操作 sql 具体的ddl sql beforeColumns afterColumns 变更前后的数据字段等等
            CanalEntry.RowChange rowChange;
            try {
                rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of event has an error , data:" + entry, e);
            }
            //获取操作类型：insert/update/delete类型
            CanalEntry.EventType eventType = rowChange.getEventType();
            //打印Header信息
            System.out.println(String.format("================》; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));
            //判断是否是DDL语句
            if (rowChange.getIsDdl()) {
                System.out.println("================》;isDdl: true,sql:" + rowChange.getSql());
            }
            //获取RowChange对象里的每一行数据, 一般对应数据库一行数据
            if(targetDataBase.equals(entry.getHeader().getSchemaName()) && targetTable.equals(entry.getHeader().getTableName())) {
                for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
                    // 删除同步
                    if (eventType == CanalEntry.EventType.DELETE) {
                        elasticSearchOperatorService.delete(rowData);
                    }
                    // 新增同步
                    else if (eventType == CanalEntry.EventType.INSERT) {
                        elasticSearchOperatorService.insertFromCanal(rowData);
                    }
                    // 修改同步
                    else {
                        elasticSearchOperatorService.insertFromCanal(rowData);
                    }
                }
            }
            log.info("同步："+ rowChange.getRowDatasList().size() + "条数据至ES成功");
        }
    }
}
